package service;

import mapper.ContactMapper;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import pojo.Contact;
import pojo.UserContact;
import util.SqlSessionFactoryUtil;

import java.util.List;

public class ContactService {
    private final SqlSessionFactory sqlSessionFactory = SqlSessionFactoryUtil.getSqlSessionFactory();

    public List<Contact> selectContactOfID(Contact contact) {
        SqlSession sqlSession = sqlSessionFactory.openSession();
        ContactMapper contactMapper = sqlSession.getMapper(ContactMapper.class);

        List<Contact> contacts = contactMapper.selectContactOfID(contact.get_ID());

        sqlSession.close();
        return contacts;
    }

    public List<UserContact> selectUserContactOfUserContact(UserContact userContact) {
        SqlSession sqlSession = sqlSessionFactory.openSession();
        ContactMapper contactMapper = sqlSession.getMapper(ContactMapper.class);

        List<UserContact> userContacts = contactMapper.selectUserContactOfUserContact(userContact.get_userNo(), userContact.get_ID());

        sqlSession.close();
        return userContacts;
    }

    public List<Contact> selectContactsOfUserNo(String userNo) {
        SqlSession sqlSession = sqlSessionFactory.openSession();
        ContactMapper contactMapper = sqlSession.getMapper(ContactMapper.class);

        List<Contact> contacts = contactMapper.selectContactsOfUserNo(userNo);

        sqlSession.close();
        return contacts;
    }

    public void deleteContactLinkOfUser(UserContact userContact) {
        SqlSession sqlSession = sqlSessionFactory.openSession();
        ContactMapper contactMapper = sqlSession.getMapper(ContactMapper.class);

        contactMapper.deleteContactLink(userContact.get_userNo(), userContact.get_ID());

        // 提交删除事务
        sqlSession.commit();
        sqlSession.close();
    }

    public void addContactLink(UserContact userContact) {
        SqlSession sqlSession = sqlSessionFactory.openSession();
        ContactMapper contactMapper = sqlSession.getMapper(ContactMapper.class);

        contactMapper.addContactLink(userContact.get_userNo(), userContact.get_ID());

        sqlSession.commit();
        sqlSession.close();
    }

    public void addContact(Contact contact) {
        SqlSession sqlSession = sqlSessionFactory.openSession();
        ContactMapper contactMapper = sqlSession.getMapper(ContactMapper.class);

        List<Contact> contacts = contactMapper.selectContactOfID(contact.get_ID());
        if (contacts.isEmpty()) {
            contactMapper.addContact(contact.get_ID(),
                    contact.get_trueName(),
                    contact.get_sex(),
                    contact.get_teleNum());
            sqlSession.commit();
        }

        sqlSession.close();
    }
}
